//
//  XLHomeListViewModel.swift
//  SinaProjectTest
//
//  Created by zhanghaifeng on 16/10/26.
//  Copyright © 2016年 BBSWaitting. All rights reserved.
//

import UIKit
import SDWebImage

class XLHomeListViewModel: NSObject {
    
    // 定义全局的数组接收微博数据
    var dataArray: [XLHomeViewModel] = [XLHomeViewModel]()

    func loadHomeListData(isPullUp: Bool, finish:@escaping (Bool, String) -> ()){
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        if isPullUp{
            maxId = dataArray.last?.statusModel?.id ?? 0
            if maxId > 0{
                maxId -= 1
            }
            sinceId = 0
        }else{
            sinceId = dataArray.first?.statusModel?.id ?? 0
            maxId = 0
        }
        
        let message: String = "没有加载到最新的微博数据"
        
        HMNetworkTools.sharedTools.loadHomeData(sinceId: sinceId, maxId: maxId, success: { (response) in
            guard let resDict = response as? [String: Any] else{
                //                print("可能为空 可能转不成字典")
                finish(false, message)
                return
            }
            // 判断 resDict 是否为空 是否转为数组
            guard let resArr = resDict["statuses"] as? [[String: Any]] else{
                //                print("可能为nil 可能转不成数组")
                finish(false, message)
                return
            }
            // 利用YYModel 转为数组
            let statusArr = NSArray.yy_modelArray(with: XLHomeStatusModel.self, json: resArr) as! [XLHomeStatusModel]
            
            // 创建一个 viewModel 的空数组
            var tmpArr:[XLHomeViewModel] = [XLHomeViewModel]()
            
            for model in statusArr{
                let statusViewModel = XLHomeViewModel()
                statusViewModel.statusModel = model
                tmpArr.append(statusViewModel)
            }
            
            // 如果是下拉加载更多 保存数据
            if isPullUp{
                self.dataArray = self.dataArray + tmpArr
            }else{
                // 下拉刷新
                self.dataArray = tmpArr + self.dataArray
            }
            self.loadSingleImage(array: tmpArr, finish: finish)
            
            }) { (error) in
                finish(false, message)
        }
    }
}

extension XLHomeListViewModel{
    // 单张图片下载
    func loadSingleImage(array: [XLHomeViewModel], finish:@escaping (Bool, String) -> ()){
        
        // 创建调度组
        let group = DispatchGroup()
        // 遍历数组
        for statusViewModel in array{
            // 如果是原创微博且count ==  1
            if statusViewModel.statusModel?.pic_urls?.count == 1{
                
                group.enter()
                
                let url = URL(string: statusViewModel.statusModel?.pic_urls?.first?.thumbnail_pic ?? "")!
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("原创微博图片下载完成")
                    group.leave()
                })
            }
            
            // 如果是转发微博 && count == 1
            if statusViewModel.statusModel?.retweeted_status?.pic_urls?.count == 1 {
                
                group.enter()
                
                let url = URL(string: statusViewModel.statusModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? "")!
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("转发微博图片下载完成")
                    
                    group.leave()
                })
            }
        }
        
        // 调度组统一监听单张图片是否下载完成
        group.notify(queue: .main) { 
            print("所有图片下载完成")
            var message = "没有加载到最新微博数据"
            if array.count > 0{
                message = "加载了\(array.count)条微博数据"
            }
            // 代表成功
            finish(true, message)
        }
        
    }

}



